﻿using System.Collections;
using System.Web.Util;
namespace System.Web
{
    internal abstract class BufferAllocator
    {
        private Stack _buffers = new Stack();
        private int _maxFree;
        private int _numFree = 0;
        private static int _procsFudgeFactor = SystemInfo.GetNumProcessCPUs();

        static BufferAllocator()
        {
            if (_procsFudgeFactor < 1)
                _procsFudgeFactor = 1;
            if (_procsFudgeFactor > 4)
                _procsFudgeFactor = 4;
        }

        internal BufferAllocator(int maxFree)
        {
            _maxFree = maxFree * _procsFudgeFactor;
        }

        protected abstract object AllocBuffer();

        internal object GetBuffer()
        {
            object obj2 = null;
            if (_numFree > 0)
                lock (this)
                    if (_numFree > 0)
                    {
                        obj2 = _buffers.Pop();
                        _numFree--;
                    }
            if (obj2 == null)
                obj2 = AllocBuffer();
            return obj2;
        }

        internal void ReuseBuffer(object buffer)
        {
            if (_numFree < _maxFree)
                lock (this)
                    if (_numFree < _maxFree)
                    {
                        _buffers.Push(buffer);
                        _numFree++;
                    }
        }
    }
}
